#include "Bits8Sequence.h"

namespace miniprojeto {
namespace util {

Bits8Sequence::Bits8Sequence(unsigned char sequence) {
	this->sequence = sequence;
}

void Bits8Sequence::printBin(int group) {
	if (!(group >= 0) && (group <= 8)) {
		BadArgumentException excep ((char*)"Bits8Sequence::printBin(int group)");
		throw excep;	
	}
	if (group == 0) {
		for (int i = 7; i >= 0; i--) {
			cout<<((sequence >> i) & 1);
		}
	} else {
		for (int i = 7, j = 1; i >= 0; i--, j++) {
			cout<<((sequence >> i) & 1);
			if (j % group == 0)
				cout<<" ";
		}
	}
	cout<<endl;
}

void Bits8Sequence::printHex(int group) {
	if (!(group >= 0) && (group < 2)) {
		BadArgumentException excep ((char*)"Bits8Sequence::printHex()");
		throw excep;	
	}
	if (group == 0) {
		for (int i = 1; i >= 0; i--) {
			cout<<hex<<((sequence >> i*4) & 0xF);
		}
	} else {
		for (int i = 1, j = 1; i >= 0; i--, j++) {
			cout<<hex<<((sequence >> i*4) & 0xF);
			if (j % group == 0)
				cout<<" ";
		}
	}
	cout<<dec<<endl;
}
	
void Bits8Sequence::printDec() {
	cout<<sequence<<endl;	
}

void Bits8Sequence::deslocLeft(int n) {
	if (!(n >= 0) && (n <= 8)) {
		BadArgumentException excep ((char*)"Bits8Sequence::deslocLeft(int n)");
		throw excep;	
	} else {
		this->sequence = sequence << n;
	}		
}

void Bits8Sequence::deslocRight(int n) {
	if (!(n >= 0) && (n <= 8)) {
		BadArgumentException excep ((char*)"Bits8Sequence::deslocRight(int n)");
		throw excep;	
	} else {
		this->sequence = sequence >> n;
	}
}

bool Bits8Sequence::isBitN(int n, BitValue value) {
	unsigned char temp = getSequence() >> n;
	temp = temp & 0x1;
	return ((bool) temp == value);
}

void Bits8Sequence::setBitN(int n, BitValue value) {
	unsigned char masc;
	if (value == ONE) {
		masc = 1; /* todos os bits 0 exceto o primeiro*/	
		masc = masc << n;
		sequence = sequence | masc;
	} else if (value == ZERO) {
		masc = 0xfe; /* todos os bits 1 exceto o primeiro*/
		for (int i = 0; i < n; i++) {
			masc = (masc << 1) | 1;	
		}	
		sequence = sequence & masc;
	}
	
}

void Bits8Sequence::clrBitN(int n) {
	setBitN(n, ZERO);
}

unsigned char Bits8Sequence::getSequence() {
	return sequence;	
}

void Bits8Sequence::binaryAnd(Bits8Sequence* s) {
	sequence = sequence & s->getSequence();
}
	
void Bits8Sequence::binaryAnd(unsigned char i) {
	sequence = sequence & i;	
}
	
void Bits8Sequence::binaryOr(Bits8Sequence* s) {
	sequence = sequence | (s->getSequence());
}

void Bits8Sequence::binaryOr(unsigned char i) {
	sequence = sequence | i;	
}
	

void Bits8Sequence::binaryXor(Bits8Sequence* s) {
	sequence = sequence ^ s->getSequence();
}

void Bits8Sequence::clrSequence() {
	this->sequence = 0x0;	
}

	
void Bits8Sequence::binaryXor(unsigned char i){
	sequence = sequence ^ i;	
}
	
void Bits8Sequence::binaryNot() {
	sequence = ~sequence;	
}
}
}
